/*
SendStream.java
Copyright (C) 2010  Belledonne Communications, Grenoble, France

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package mypackage.stream;

import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.RecordControl;
import mypackage.EchoScreen;
import net.rim.device.api.media.control.AudioPathControl;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.RadioInfo;

public class SendStream implements PlayerListener
{

    private Player mPlayer;

    private DatagramConnection mConnection;

    private byte[] mTransBuffer;

    private String sDestUri;

    private long time = 0;

    private boolean firstTime = true;

    private OutputStream mOutput = new OutputStream()
    {

        public void close() throws IOException
        {
        }

        public void flush() throws IOException
        {

        }

        public void write(byte[] buffer, int offset, int count)
        {
//             EchoScreen.log("SendStream===write===" + "count:" + count
//             + " time:" + (System.currentTimeMillis() - time));
            int lOffset = offset;

            // mTransBuffer[0] = (byte) 0xf0;

            time = System.currentTimeMillis();
            Datagram dg;

            int writeB = 0;
            if (firstTime)
            {
                lOffset += "#!AMR\n".length();
                firstTime = false;
            }

            //send amr
            mTransBuffer = new byte[32];
            while (writeB + 32 <= count)
            {
                try
                {
                    System.arraycopy(buffer, lOffset + writeB,
                        mTransBuffer, 0, 32);
                    dg = mConnection.newDatagram(mTransBuffer, 32, sDestUri);
                    mConnection.send(dg);
                    writeB += 32;
                }
                catch (IOException e)
                {
                    EchoScreen.log("send udp ecxeption:" + e.toString());
                    e.printStackTrace();
                }
            }
            
        }

        public void write(byte[] buffer) throws IOException
        {
            write(buffer, 0, buffer.length);
        }

        public void write(int arg0) throws IOException
        {

        }
    };

    public SendStream(String address, DatagramConnection connection)
    {
        mConnection = connection;
        if ("".equals(address))
        {
            sDestUri = "datagram://" + "10.60.5.62" + ":38858";
        }
        else
        {
            sDestUri = "datagram://" + address + ":38858";
        }
    }

    public void stop()
    {
        try
        {
            RecordControl recordControl = (RecordControl) mPlayer
                .getControl("RecordControl");
            recordControl.commit();
            mOutput.close();
            mPlayer.close();
        }
        catch (Throwable e)
        {
        }

    }

    public void start()
    {
        try
        {
            mPlayer = Manager
                .createPlayer("capture://audio?encoding=audio/amr&updateMethod=time&updateThreshold=20");
            
            mPlayer.addPlayerListener(this);
            mPlayer.realize();
            RecordControl recordControl = (RecordControl) mPlayer
                .getControl("RecordControl");
            recordControl.setRecordStream(mOutput);

            recordControl.startRecord();
            AudioPathControl lPathCtr = (AudioPathControl) mPlayer
                .getControl("net.rim.device.api.media.control.AudioPathControl");
            lPathCtr.setAudioPath(AudioPathControl.AUDIO_PATH_HANDSET);
            mPlayer.prefetch();
            mPlayer.start();
        }
        catch (Throwable e)
        {
            EchoScreen.log("SendStream start exception:" + e.toString());
        }

    }

    public void playerUpdate(Player arg0, String event, Object eventData)
    {
        /*
         * if (isStarted && event.equals(PlayerListener.RECORD_STOPPED )) {
         * sLogger.warn("Unexpected recorder stop, restarting"); RecordControl
         * recordControl = (RecordControl) mPlayer.getControl("RecordControl");
         * recordControl.startRecord(); }
         */
    }

    protected Player getPlayer()
    {
        return mPlayer;
    }
}
